package com.ssdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssdp.constant.PageConstant;
import com.ssdp.constant.RedisConstant;
import com.ssdp.dto.Result;
import com.ssdp.dto.ScrollResult;
import com.ssdp.dto.UserDTO;
import com.ssdp.entity.Blog;
import com.ssdp.entity.Follow;
import com.ssdp.entity.User;
import com.ssdp.mapper.BlogMapper;
import com.ssdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssdp.service.IFollowService;
import com.ssdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.ssdp.constant.RedisConstant.BLOG_LIKED_KEY;
import static com.ssdp.constant.RedisConstant.FEED_KEY;

/**
 * @author syo 2319615164@qq.com
 * @description Blog服务
 * @date 2024/3/14
 * @Copyright syo
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    private final UserServiceImpl userService;

    private final BlogMapper blogMapper;

    private final StringRedisTemplate stringRedisTemplate;

    private final IFollowService followService;

    /**
     * 根据博客Id查询博客详情
     * @param id 博客Id
     * @return 结果
     */
    @Override
    public Result queryBlogById(Long id) {
        // 1. 查询blog
        Blog blog = blogMapper.selectById(id);
        if(blog == null) {
            return Result.fail("博客不存在!");
        }

        // 2. 查询blog相关的用户
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        isBlogLiked(blog);
        return Result.ok(blog);
    }

    /**
     * 判断当前用户是否已经给当前博客点赞了
     * @param blog 博客
     */
    private void isBlogLiked(Blog blog) {
        // 1. 获取当前登录用户

        if(UserHolder.getUser() == null ) return;
        Long userId = UserHolder.getUser().getId();

        String key = RedisConstant.BLOG_LIKED_KEY + blog.getId();

        // 2.判断当前登录用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    /**
     * 查询最热的博客
     * @param current 分页参数
     * @return 结果
     */
    @Override
    public Result queryHotBlog(Integer current) {

        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, PageConstant.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            isBlogLiked(blog);
        });


        return Result.ok(records);
    }

    /**
     * 点赞博客
     * @param id 博客Id
     * @return 结果
     */
    @Override
    public Result likeBlog(Long id) {
        // 1. 获取当前登录用户
        Long userId = UserHolder.getUser().getId();

        String key = RedisConstant.BLOG_LIKED_KEY + id;

        // 2.判断当前登录用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        // 3. 如果未点赞，可以点赞
        if(score == null) {
            // 3.1 数据库点赞数 + 1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if(isSuccess) {
                // 3.2 保存用户到redis的set集合
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
            // 4. 如果已点赞,取消点赞
        } else {
            // 4.1 数据库点赞数-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();

            // 4.2 把用户从redis中的set集合中移出
            if(isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }

        return Result.ok("");
    }

    /**
     * 查询当前博客最开始点赞的5个人
     * @param id 博客Id
     * @return 结果
     */
    @Override
    public Result queryBlogLikes(Long id) {
        // 1.查询top5
        String key = RedisConstant.BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);

        if(top5 == null || top5.size() == 0) return Result.ok(Collections.emptyList());

        // 2. 解析除用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());

        String idStr = StrUtil.join(",", ids);

        // 3. 根据用户id查询用户
        List<UserDTO> userDTOS = userService.query().in("id", ids).last("order by field(id," + idStr +")").list()
                .stream().map(item -> {
            return BeanUtil.copyProperties(item, UserDTO.class);
        }).collect(Collectors.toList());


        return Result.ok(userDTOS);
    }

    /**
     * 保存博客
     * @param blog 博客详情
     * @return 结果
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 1. 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());

        // 2. 保存探店博文
        try {
            if(StrUtil.isBlank(blog.getImages())) {
                throw new RuntimeException("图片不能为空");
            }
            boolean isSuccess = save(blog);

            if(!isSuccess) return Result.fail("新增笔记失败！");
            // 3. 将博客的id发送给所有的粉丝
            // 3.1 查询所有粉丝
            List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
            long publishTime = System.currentTimeMillis();
            for (Follow follow : follows) {
                // 3.2 获取粉丝id
                Long userId = follow.getUserId();

                // 3.3 推送笔记id给所有粉丝
                String key = RedisConstant.FEED_KEY + userId;
                stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), publishTime);
            }

        } catch (Exception e) {
            log.error("发生了异常：{}", e.getMessage());
            return Result.fail("图片、内容、标题和关联商户不能为空！");
        }

        // 4. 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 获取关注的博客
     * @param max 最大分数（由前端时间）
     * @param offset 偏移（最大分数条目向下偏移条目）
     * @return 滚动分页结果
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1. 获取当前用户(并得到收件箱地址)
        Long id = UserHolder.getUser().getId();
        String key = RedisConstant.FEED_KEY + id;

        // 2. 查询收件箱
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 3);

        // 3. 非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }

        // 用于保存当前分页的ids
        ArrayList<Long> ids = new ArrayList<>(typedTuples.size());

        // 用于保存当前分页最小时间
        long minTime = 0;
        int os = 1;
        // 4. 解析收件箱（blog id  对应的分数score， offset）
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            // 4.1 获取id
            ids.add(Long.valueOf(typedTuple.getValue()));

            // 4.2 获取时间戳
            long l = typedTuple.getScore().longValue();
            if(l != minTime) {
                minTime = l;
                os = 1;
            } else {
                os++;
            }
        }

        // 5. 根据id查询blog （使用拼接的方式能够按照我们想要的顺序得到）
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("order by field(id," + idStr +")").list();

        // 5.1 将每一个blog填充完整的信息
        for (Blog blog : blogs) {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            isBlogLiked(blog);
        }

        // 6. 封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }
}
